var c = 1;
var len;
var __trainList = [];
var __filterDataList = [];
var __ArrStations = [];
var __DepStations = [];
//车型搜索条件
var __TypeList = [];
//出发时间段
var __DepPer = [];
//到达时间段
var __ArrPer = [];
//出发站台
var __DepPlat = [];
//到达站台
var __ArrPlat = [];
//始发
var __isDirect = [];

//过路
var __isnotDirect = [];

function initSearchBox() {
    if (SearchBox != null) {
        //    parm = SearchBox.GoTime;
        $("#traveltype").val(SearchBox.SearchType);
        if (SearchBox.DepartCity != null && SearchBox.DepartCity.length > 1) {
            SetCityContainer("notice01", SearchBox.DepartCity);
        }
        if (SearchBox.ArriveCity != null && SearchBox.ArriveCity.length > 1) {
            SetCityContainer("notice02", SearchBox.ArriveCity);
        }
        if (SearchBox.DepartDate != "") {
            $("#txtDepartDate").val(SearchBox.DepartDate);
            c = DateDiff("d", dateParse($("#hdTodayDate").val()), dateParse(SearchBox.DepartDate));
        }

        if (SearchBox.BackDate != "") {
            $("#txtreturndate").val(SearchBox.BackDate);
        }

        $("#BookingSelf").removeAttr("disabled"); $("#BookingOther").removeAttr("disabled");
        $("#fee_od_box2").show();
        $('[name="CorpPayTypeRadio"]').change(function () {
            if ($(this).val() == "OWN") {
                $("#BookingOther").attr("disabled", true).removeAttr("checked");
                $("#BookingSelf").attr("disabled", true).removeAttr("checked");
            }
            else {
                $("#BookingSelf").removeAttr("disabled");
                $("#BookingOther").removeAttr("disabled");
                if (OrderForSelf == '1') {
                    $('#BookingOther').attr("disabled", "");
                }
                $("#BookingSelf").attr('checked', 'checked');
                $("#BookingSelf").trigger("click");
            }
            $("#btn_search").trigger("click");
        });

        if (SearchBox.FeeType != "PUB") {
            $("#BookingOther").attr("disabled", true).removeAttr("checked");
            $("#BookingSelf").attr("disabled", true).removeAttr("checked");
            $("#privateRadio").attr("checked", "checked");
            $("#publicRadio").removeAttr("checked");

        } else {
            $("#BookingSelf").removeAttr("disabled");
            $("#BookingOther").removeAttr("disabled");
            $("#publicRadio").attr("checked", "checked");
            $("#privateRadio").removeAttr("checked");
            if (OrderForSelf == '1') { $('#BookingOther').attr("disabled", ""); }
        }
        if (SearchBox.BookingType != null && SearchBox.BookingType.toUpperCase() == "OTHER") {
            $("#BookingOther").click();
            //$("#policy_c3").show();
        }
        else if (SearchBox.BookingType != null && SearchBox.BookingType.toUpperCase() == "SELF") {
            //$("#policy_c3").hide();
            $("#BookingSelf").click();
        }

    }
}


$(function () {
    initSearchBox();
    checkTrainSearch();
    $('[name="newsort"] th').eq(1).click(function () {
        $('[name="newsort"] th a').removeClass("current");
        $(this).find("a").addClass("current");
        SortList(1, this);
    });

    $('[name="newsort"] th').eq(3).click(function () {
        $('[name="newsort"] th a').removeClass("current");
        $(this).find("a").addClass("current");
        SortList(2, this);
    });

    $('#traveltype').change(function () {
        if ($('#traveltype').val() == "S") {
            $('#lblRetturnDate').css('display', 'none');
            $('#txtreturndate').css('display', 'none');
        } else {
            $('#lblRetturnDate').css('display', '');
            $('#txtreturndate').css('display', '');
        }
    });
    $('[name="CorpBookingTypeRadio"]').change(function () {
        $("#btn_search").trigger("click");
    });
    DrawList();
});

function findTrainItem(index, seat, tNo, fromStationName, toStationName, seatName) {
    var a = null;
    var t_list = jQuery.extend(true, [], __trainList);
    if (t_list != null) {
        for (var i = 0; i < t_list.length; i++) {
            if (t_list[i].train_number.replace("/", "_") == tNo && fromStationName == t_list[i].FromStationName && toStationName == t_list[i].ToStationName) {
                a = t_list[i];
                break;
            }
        }
    }

    if (a != null) {
        var s = [];
        a.DisplaySeats = "";
        a.BookBtns = "";
        for (var i = 0; i < a.seats.length; i++) {
            if (a.seats[i].seat_name == seatName) {
                s.push(a.seats[i]);
                break;
            }
        }
        a.seats = s;
    }
    return a;
}


function CombineFlightData() {

    var data = collectValues(["DepartCity1", "ArriveCity1", "DepartDate1",
            , "FeeType", "BookingType", "PassengerType", "SearchType"],
        {
            "DepartCity1": function () {
                return SearchBox.DepartCity;
            },
            "ArriveCity1": function () {
                return SearchBox.DepartCity;
            },
            "DepartDate1": function () {
            },
            "FeeType": function () {
                return SearchBox.FeeType;
            },
            "BookingType": function () {
                return SearchBox.BookingType;
            },
            "SearchType": function () {
                return SearchBox.SearchType;
            }

        });
    return data;
}


function GetTypeCondiction(type) {
    var a = [];

    var p = $(".search_cate_list a[param^=\"" + type + "_\"]").filter(".selected");
    if (!p.hasClass('show_all') && p != null && p.length > 0) {
        for (var i = 0; i < p.length; i++) {
            a.push($(p[i]).attr("param").split("_")[1]);
        }
    }
    return a;
}

function SetSearchCondiction() {
    __DepPlat = GetTypeCondiction("Dep");
    __ArrPlat = GetTypeCondiction("Arr");
    __DepPer = GetTypeCondiction("DepTime");
    __ArrPer = GetTypeCondiction("ArrTime");
    __TypeList = GetTypeCondiction("Type");
    __isDirect = GetTypeCondiction("St");
}

function SortList(type, o) {
    //var __list = __filterDataList;
    if ($(o).find("a > b").is(".icon_arrow_up")) {
        $(o).find("a > b").removeClass("icon_arrow_up").addClass("icon_arrow_down");
        if (type == 1) {
            __filterDataList.sort(function (a, b) { return a.DepTime < b.DepTime ? 1 : -1 });
        }
        else {
            __filterDataList.sort(function (a, b) { return a.Run_time < b.Run_time ? 1 : -1 });
        }
    }
    else {
        $(o).find("a > b").removeClass("icon_arrow_down").addClass("icon_arrow_up");
        if (type == 1) {
            __filterDataList.sort(function (a, b) { return a.DepTime > b.DepTime ? 1 : -1 });
        }
        else {
            __filterDataList.sort(function (a, b) { return a.Run_time > b.Run_time ? 1 : -1 });
        }
    }

    FilterData(__filterDataList);

}



//重新搜索原有数据
function ReSearch_Org_Data() {
    var data = collectValues(["SearchType", "DepartCity", "ArriveCity", "DepartDate", "BackDate", "FeeType", "BookingType"],
        {
            "SearchType": function () {
                return $("#traveltype").val();
            },
            "DepartCity": function () {
                return GetCityContainer("notice01");
            },
            "ArriveCity": function () {
                return GetCityContainer("notice02");
            },
            "DepartDate": function () {
                return $("#txtDepartDate").val() == "yyyy-mm-dd" ? "" : $("#txtDepartDate").val();
            }, "BackDate": function () {
            return $("#txtreturndate").val() == "yyyy-mm-dd" ? "" : $("#txtreturndate").val();
        }, "FeeType": function () {
            return getRadioValue("CorpPayTypeRadio");
        }, "BookingType": function () {
            return getRadioValue("CorpBookingTypeRadio");

        }
        });
    return data;
}

function DrawCondictions() {

    var ds = "<dd class=\"New_now\"><a class=\"show_all selected\" href=\"###\" param=\"Dep_all\">不限</a></dd>";
    var as = "<dd class=\"New_now\"><a class=\"show_all selected\" href=\"###\" param=\"Arr_all\">不限</a></dd>";
    for (var i = 0; i < __DepStations.length; i++) {
        ds += "<dd><a class=\"\" href=\"###\" param=\"Dep_" + __DepStations[i] + "\">" + __DepStations[i] + "</a></dd>";
    }
    for (var i = 0; i < __ArrStations.length; i++) {
        as += "<dd><a class=\"\" href=\"###\" param=\"Arr_" + __ArrStations[i] + "\">" + __ArrStations[i] + "</a></dd>";
    }
    $(ds).insertAfter($("#ddlDepCon dt"));
    $(as).insertAfter($("#ddlArrCon dt"));
}

function BookingCheck(index, no, seat, seatname, fromStationName, toStationName) {
    //    var orderRange = (ReasonCode != null ? parseInt(ReasonCode.OrderRange) : 0);
    //    if ((orderRange & 16) <= 0 && orderRange != 0) { // 火车票
    //        alert("您不能预定火车票，请联系管理员开通并重新登录。");
    //        return;
    //    }
    //    //如果没选政策执行人且只是单程:跳转政策执行人页面
    //    //如果没选政策执行人且是第二层:跳转政策执行人页面
    //    if ((PageParam.PolicyID == null || PageParam.PolicyID == "") && SearchBox.FeeType.toUpperCase() == "PUB") {
    //        Policy_Evt();
    //        return;
    //    }
    //    var data = { "FirstRoute": null, "SecondRoute": null, "RCCode1": "", "RCCode2": "" };
    //    //不在预定范围之内
    //    //    var isNeedTranRC = (SearchBox.FeeType.toUpperCase() == "OWN" || (ReasonCode != null && ReasonCode.IsNeedRC_Trn.trim() == "T")) ? true : false;
    //    //    if (!isNeedTranRC) {
    //    //        alert("您不能预定火车票，请联系管理员开通并重新登入");
    //    //        return;
    //    //    }


    //    if (!CheckTrainPolicy(no, seatname)) {
    //        if (ReasonCode.IsTrainBooking == "F") {
    //            alert("抱歉，超出差旅政策规定的可预订范围，出行人的政策标准规定不能进行违规预订。");
    //            return;
    //        }
    //        var d = { index: index, seat: seat, no: no, from: fromStationName, to: toStationName };
    //        showRC(1, d);
    //        return;
    //    }
    //    submitOrder(index, seat, no, fromStationName, toStationName);
}

function submitOrder(index, seat, no, fromStationName, toStationName,seatName) {
    var data = { "FirstRoute": null, "SecondRoute": null, "RCCode1": "", "RCCode2": "" };
    if (seat == 32) { seat = 16 }
    var t = findTrainItem(index, seat, no, fromStationName, toStationName, seatName);
    if (index == "1") {
        data.FirstRoute = t;
        //data.RCCode1 = $("#trainRC1").val();
    }

    $("#trainForm").val(ConvertObject(data));

    post2Url("Order.aspx");
}

function GetSeletedRoute(index, no, price, seatType) {
    var data = collectValues(["Sequence", "DepartCity", "ArriveCity", "DepartDate", "TrainNumber", "TrainType"],
        {
            "SearchType": function () {
                return index;
            },
            "DepartCity": function () {
                return SearchBox.DepartCity;
            },
            "ArriveCity": function () {
                return SearchBox.ArriveCity;
            },
            "DepartDate": function () {
                return SearchBox.DepartDate;
            },
            "TrainNumber": function () {
                return no;
            },
            "TrainType": function () {
                return seatType;
            }
        });
    return data;
}


function DrawList() {
    $.ajax_call('Product', 'GetTrainList', { from: SearchBox.DepartCity[0], to: SearchBox.ArriveCity[0], date: SearchBox.DepartDate }, function (resData) {
            __trainList = resData.Data.trains;
            __DepStations = resData.Data.DepStations;
            __ArrStations = resData.Data.ArrStations;
            if (__trainList != null && __trainList.length > 0) {
                for (var i = 0; i < __trainList.length; i++) {
                    __trainList[i].DisplayId = __trainList[i].train_number.replace("/", "_");
                    var t = GetTicketSeats(__trainList[i].DisplayId, __trainList[i].seats, __trainList[i].FromStationName, __trainList[i].ToStationName);
                    __trainList[i].DisplaySeats = t.Seats;
                    __trainList[i].BookBtns = t.Btns;
                }
            }
            __filterDataList = __trainList;
            $("#totalResult").html(__trainList == null ? 0 : __trainList.length);
            $('#resultTable').Repeater(__trainList);
            $("[mod=popShow]").popupshow();
            if (__trainList == null || __trainList.length == 0) {
                $("#noneFilterResult").show();
            }
            else {
                $("#noneFilterResult").hide();
            }
            DrawCondictions();


            $(".search_cate_list a").click(function () {
                // 获取当前节点同级的兄弟节点
                var siblings = $(this).parent().siblings().find('a')
                // 判断是否是‘不限’按钮
                if ($(this).hasClass('show_all')) {
                    siblings.removeClass("selected").removeAttr('checked');
                    $(this).addClass("selected");
                } else {
                    if ($(this).is(".selected")) {
                        if (!siblings.hasClass('selected')) {
                            siblings.filter('.show_all').addClass("selected");
                        }
                        $(this).removeClass("selected");
                    }
                    else {
                        $(this).addClass("selected");
                        if (siblings.filter('.show_all').hasClass('selected')) {
                            siblings.filter('.show_all').removeClass("selected");
                        }
                    }
                }

                SetSearchCondiction();
                FilterData(__filterDataList);
            });


            var _obj = $("#search_goTime a:gt(0)");
            for (var i = 0; i < _obj.length; i++) {
                var s = $(_obj[i]).attr("param");
                if (s == goTime) {
                    $(_obj[i]).trigger("click");
                }
            }

        },
        function () {
            alert("系统繁忙，稍后请重试");
        },
        null
    );

}




function CheckHasSelected(tp, compare) {

    if (tp == "Type") {
        if (__TypeList == null || __TypeList.length == 0) {
            return true;
        }
        for (var i = 0; i < __TypeList.length; i++) {
            var s = __TypeList[i].split("/");
            for (var j = 0; j < s.length; j++) {
                var item = s[j];
                if (item == "N") {
                    if (compare.indexOf("L") > -1 || !isNaN(compare) || compare.indexOf("Y") > -1) {
                        return true;
                    }
                }
                if (compare.indexOf(item) > -1) {
                    return true;
                }
            }
        }
    }
    else if (tp == "DepTime") {
        if (__DepPer == null || __DepPer.length == 0) {
            return true;
        }
        for (var i = 0; i < __DepPer.length; i++) {
            var v = __DepPer[i].split("|");
            if (IncludeTimePeriod(compare, v[0], v[1])) {
                return true;
            }
        }
    }
    else if (tp == "ArrTime") {
        if (__ArrPer == null || __ArrPer.length == 0) {
            return true;
        }
        for (var i = 0; i < __ArrPer.length; i++) {
            var v = __ArrPer[i].split("|");
            if (IncludeTimePeriod(compare, v[0], v[1])) {
                return true;
            }
        }
    }
    else if (tp == "Arr") {
        if (__ArrPlat == null || __ArrPlat.length == 0) {
            return true;
        }
        for (var i = 0; i < __ArrPlat.length; i++) {
            if (__ArrPlat[i] == compare) {
                return true;
            }
        }
    }
    else if (tp == "Dep") {
        if (__DepPlat == null || __DepPlat.length == 0) {
            return true;
        }

        for (var i = 0; i < __DepPlat.length; i++) {
            if (__DepPlat[i] == compare) {
                return true;
            }
        }
    }
    else if (tp == "St") {
        if (__isDirect == null || __isDirect.length == 0) {
            return true;
        }

        if (__isDirect.length == 2) {
            return true;
        }

        for (var i = 0; i < __isDirect.length; i++) {
            if (__isDirect[i] == "d") {

                return compare == true;
            }
            else {
                return compare == false;
            }
        }
    }
    return false;
}

function FilterData(d) {
    var v = [];
    for (var i = 0; i < d.length; i++) {

        if (CheckHasSelected("Type", d[i].train_number) && CheckHasSelected("DepTime", d[i].DepTime)
            && CheckHasSelected("ArrTime", d[i].ArriveTime) && CheckHasSelected("Dep", d[i].FromStationName)
            && CheckHasSelected("Arr", d[i].ToStationName) && CheckHasSelected("St", d[i].IsFirstStation)) {

            v.push(d[i]);
        }
    }
    $('#resultTable').Repeater(v);
    if (v == null || v.length == 0) {
        $("#noneFilterResult").show();
    }
    else {
        $("#noneFilterResult").hide();
    }
    $("[mod=popShow]").popupshow();
}


function showStationTag(isD, directCss) {
    if (isD) {
        return "<span class=" + directCss + "></span>";
    }
    else {
        return "<span class=\"icon_pass\"></span>";
    }
}

function filterShowAlternate() {
    if ($("#filterControllerIcon").hasClass("icon_hide")) {
        $("#filterControllerIcon").removeClass("icon_hide").addClass("icon_show");
    } else {
        $("#filterControllerIcon").removeClass("icon_show").addClass("icon_hide");
    }
    $("#resultFilters dl:gt(1)").toggle();


}



function GetTicketSeats(tNo, seats, fromStationName, toStationName) {
    var s = "";
    var b = "";
    var show = { "Seats": "", "Btns": "" };

    //软卧
    var rIDList = ["软卧上", "软卧中","软卧下"];
    //硬卧
    var yIDList = ["硬卧上", "硬卧中", "硬卧下"];
    var dIdList = ["动卧上", "动卧下"];
    var grIDList = ["高级软卧上","高级软卧下"];
    if (seats != null && seats.length > 0) {
        for (var i = 0; i < seats.length; i++) {
            //软卧、硬卧
            if (rIDList.indexOf(seats[i].seat_name) > -1 || yIDList.indexOf(seats[i].seat_name) > -1 || dIdList.indexOf(seats[i].seat_name) > -1 || grIDList.indexOf(seats[i].seat_name) > -1) {
                //只展示下铺价格
                if (seats[i].seat_name.indexOf("下") <= -1) {
                    continue;
                }
                if (parseInt(seats[i].seat_bookable) > 0) {
                    b += "<input type=\"button\" id=\"" + tNo + "\" class=\"btn_book\" value=\"预订\" onclick=\"SelectTrain.CheckYuPiao(this,1,'" + tNo + "',8,'" + seats[i].seat_name + "','" + fromStationName + "','" + toStationName + "')\"><br />";
                }
                else {
                    b += "<input type=\"button\" id=\"" + tNo + "\" class=\"btn_book disable\" value=\"预订\"><br />";
                }

                //座位名
                s += "<div class=\"railway_seat\" id=\"ticketdiv" + tNo + "\"><div style='float:left;'>" + seats[i].seat_name.substring(0, seats[i].seat_name.length - 1) + "<dfn>&yen;</dfn><img alt=\"\" style=\"display: none\" id=\"ticketimg" + seats[i].seat_id + "\" src=\"/WebResource/common/images/loading.gif\">";
                //价格
                s += "<span class=\"base_price " + (parseInt(seats[i].seat_bookable) > 0 ? "base_pricePop" : "base_txtgray") + "\" id=\"sPrice" + tNo + "\"";

                if (parseInt(seats[i].seat_bookable) > 0) {
                    s += "onmouseenter=\"labelShow.show(this)\" onmouseleave=\"labelShow.hide(this)\"";
                }
                s += ">" + seats[i].seat_price + "</span>";
                //余票
                s += "</div><span class=\"yupiao\">余<span style=\"" + ((seats[i].seat_yupiao > 10 || seats[i].seat_yupiao == 0) ? "" : "color: #e56700") + "\">" + seats[i].seat_yupiao + "</span>张</span></div>";
            }
            else {
                //其他
                if (parseInt(seats[i].seat_bookable) > 0) {
                    if (seats[i].seat_name != "高级软卧") {
                        b += "<input type=\"button\" id=\"" + tNo + "\" class=\"btn_book\" value=\"预订\" onclick=\"SelectTrain.CheckYuPiao(this,1,'" + tNo + "','" + seats[i].seat_id + "'" + ",'" + seats[i].seat_name + "','" + fromStationName + "','" + toStationName + "');\">";
                    } else {
                        b += "<input type=\"button\" id=\"" + tNo + "\" class=\"btn_book\" value=\"预订\" onclick=\"SelectTrain.CheckYuPiao(this,1,'" + tNo + "','" + 32 + "'" + ",'" + seats[i].seat_name + "','" + fromStationName + "','" + toStationName + "');\">";
                    }
                    s += "<div class=\"railway_seat\" id=\"ticketdiv" + tNo + "\"><div style='float:left;'>" + seats[i].seat_name + "<dfn>&yen;</dfn><img alt=\"\" style=\"display: none\" id=\"ticketimg" + seats[i].seat_id + "\" src=\"/WebResource/common/images/loading.gif\"><span class=\"base_price\" id=\"sPrice" + tNo + "\">" + seats[i].seat_price + "</span></div><span class=\"yupiao\">余<span style=\"" + ((seats[i].seat_yupiao > 10 || seats[i].seat_yupiao == 0) ? "" : "color: #e56700") + "\">" + seats[i].seat_yupiao + "</span>张</span></div>";
                }
                else {
                    b += "<input type=\"button\" id=\"" + tNo + "\" class=\"btn_book disable\" value=\"预订\">";

                    s += "<div class=\"railway_seat\" id=\"ticketdiv" + tNo + "\"><div style='float:left;'>" + seats[i].seat_name + "<dfn>&yen;</dfn><img alt=\"\" style=\"display: none\" id=\"ticketimg" + seats[i].seat_id + "\" src=\"/WebResource/common/images/loading.gif\"><span class=\"base_price base_txtgray\" id=\"sPrice" + tNo + "\">" + seats[i].seat_price + "</span></div><span class=\"yupiao\">余<span style=\"" + ((seats[i].seat_yupiao > 10 || seats[i].seat_yupiao == 0) ? "" : "color: #e56700") + "\">" + seats[i].seat_yupiao + "</span>张</span></div>";
                }

                if (i != seats.length - 1) {
                    b += "<br />";
                }
            }
        }
    }
    show.Seats = s;
    show.Btns = b.trim();
    return show;
}
String.prototype.trimStart = function (trimStr) {
    if (!trimStr) { return this; }
    var temp = this;
    while (true) {
        if (temp.substr(0, trimStr.length) != trimStr) {
            break;
        }
        temp = temp.substr(trimStr.length);
    }
    return temp;
};

//软卧、硬卧价格处的提示浮层
var labelShow = (function () {
    var flag = false, div;
    return {
        alertModel: function () {
            if (!flag) {
                var div1 = document.createElement('div');
                var p = document.createElement('p');
                div1.className = 'base_pricePopCount hiddden';
                div1.appendChild(p);
                flag = true;
                document.body.appendChild(div1);
                div = div1;
                return div1;
            } else {
                return div;
            }
        },
        show: function (self) {//onmouseenter调用
            var x = $(self).offset().left;
            var y = $(self).offset().top + 23;
            var ele = labelShow.alertModel();
            labelShow.writeMsg($(self).text(), self);
            $(ele).css({ 'top': y, 'left': x }).show();
        },
        hide: function (self) {//onmouseleave调用
            $(labelShow.alertModel()).hide();
        },
        writeMsg: function (price, self) { //用于绘制 信息
            var txt = $(self).parent().text().substring(0, 2);
            var count = "注：卧铺上\\";
            if (txt == "硬卧") {
                count += "中\\";
            }
            count += "下是随机分配的，先按参考价" + price + "元（下铺价格）收费，<span>如有差价则3-5个工作日退回</span>。为老人或孕妇购买下铺票，建议您到车站或代售点购买。";
            var ele = labelShow.alertModel();
            var innerWrap = $(ele).find('p');
            $(innerWrap).html(count);
        }
    }

})();


